package com.gl.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.come.bean.Skill;
import org.come.until.UserMessUntil;

/**
 *
 * 灵犀工具类
 * 
 * @author BigGreen
 *
 */
public class LingXiUtil {
	
	/**
	 * 解析灵犀字符串返回技能格数量（已开启的）
	 * @param lingxi
	 * @return
	 */
	public static int getLingXiGe(String lingxi){
		if (StringUtils.isNotEmpty(lingxi)) {
			String param[] = lingxi.split("&");
	    	// 灵犀技能
	    	String jn = param[3].split("=")[1];
	    	String[] jineng = jn.split("\\|");
	    	return jineng.length < 10 ? 0 : jineng.length - 10;
		}
		return 0;
	}
	
	/**
	 * 返回灵犀点数
	 * @param lingxi
	 * @return
	 */
	public static int getPointCount(String lingxi) {
		if (StringUtils.isNotEmpty(lingxi)) {
			String param[] = lingxi.split("&");
	    	String dj = param[2].split("=")[1];
    		return Integer.parseInt(dj);
		}
		return 0;
	}
	
	/**
	 * 查找并返回灵犀技能对应值，如果没有则返回0
	 * @param lingxi
	 * @param skillid
	 * @param idx
	 * @return
	 */
	public static int getNumberByStr(String lingxi,String skillid, int idx) {
		if (StringUtils.isNotEmpty(lingxi)) {
			String param[] = lingxi.split("&");
	    	// 灵犀技能
	    	String jn = param[3].split("=")[1];
	    	String[] jineng = jn.split("\\|");
	    	for (String jnstr : jineng) {
	    		String[] jns = jnstr.split("_");
	    		if (jns[0].equals(skillid)) {
	    			if ("0".equals(jns[1])) {
	    				return 0;
	    			}
	    			Skill skill = UserMessUntil.getSkillId(skillid);
	    			if (skill == null) {
	    				return 0;
	    			}
	    			return getNumber(skill,idx,jns[1]);
	    		}
	    	}
		}
		return 0;
	}
	
	
	/**
	 * 根据灵犀技能ID获取灵犀值
	 * @param skillid
	 * @param lvl
	 * @return
	 */
	public static int getNumberBySkillId(String skillid, int idx ,int lvl) {
		Skill skill = UserMessUntil.getSkillId(skillid);
		if (skill == null) {
			return 0;
		}
		return getNumber(skill,idx,lvl + "");
	}
	

	/**
	 * 计算灵犀技能数值公式
	 * 
	 * @param skill
	 * @param idx   第几个数值
	 * @return
	 */
	public static int getNumber(Skill skill, int idx,String dj) {

		String msg = skill.getRemark();
		if (!StringUtils.isNotEmpty(skill.getRemark())) {
			return 0;
		}
		
		int lvl = Integer.parseInt(dj);
		
		if (lvl == 0) {
			return 0;
		}
		lvl--;
		
		Matcher mat = Pattern.compile("<([^>]*)>").matcher(msg);
		
		int i = 1;
		while (mat.find()) {
			if (i != idx) {
				continue;
			}
			String str = mat.group();
			str = str.replaceAll("<", "").replaceAll(">", "");
			if (str.indexOf("+") > -1) {
				String[] num = str.split("\\+");
				if (num.length == 2) {
					double s = Double.parseDouble(num[0]);
					double e = Double.parseDouble(num[1]);
					return (int)(s + e * lvl);
				}
			} else if (str.indexOf("-") > -1) {
				String[] num = str.split("-");
				if (num.length == 2) {
					double s = Double.parseDouble(num[0]);
					double e = Double.parseDouble(num[1]);
					return (int)(s - e * lvl);
				}
			}
		}
		return 0;
	}

}
